/*
 * @Author: wangtao
 * @Date: 2020-07-11 15:43:52
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-08-12 16:11:02
 * @Description: 路由管理文件
 */
import React from 'react';
import { Platform, PixelRatio } from 'react-native';
import { createAppContainer, NavigationActions } from 'react-navigation';
import {
  createStackNavigator,
  StackViewStyleInterpolator,
} from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { BackImageOn, } from '@/common';
import { px2dp, } from '@/styles';

// 测试页面start
import Test from './pages/test';
import ListViewDemo from './pages/test/listview';
import IQKeyboardManager from './pages/test/IQKeyboardManager';
// 测试页面end

// 基础页面
import RoleSwitch from './pages/user-common/role-switch';
import Setting from './pages/user-common/setting';
import UserFeedback from './pages/user-common/user-feedback';// 用户反馈
import AccountCenter from './pages/user-common/account-center';// 账号安全
import ChangePhoneConform from './pages/user-common/account-center/change-phone-con';
import ChangePhoneNew from './pages/user-common/account-center/change-phone-new';
import ChangePhone from './pages/user-common/account-center/change-phone';
import LoginView from './pages/login-view';
import Welcome from './pages/welcome';
import InputMobile from './pages/login-view/reset-password/input-mobile'; // 输入手机号
import InputCode from './pages/login-view/reset-password/input-code'; // 输入验证码
import SetPassword from './pages/login-view/set-password'; // 设置密码
import MobileBind from './pages/login-view/bind-mobile';
import FeedBackDriverCer from './components/feedback-driver-cer'; // 司机认证反馈页
import CustAgreement from './components/CustAgreement'; // 协议
import IdCardCertif from './pages/user-common/step/IdsCard'; // 实名认证
import CertificationProgress from './pages/user-common/certi-progress'; // 司机认证
import ContractSYSList from './pages/contract-system/contract-sys-list'; // 合同及协议
import ContractDetail from './pages/contract-system/contract-detail'; // 合同详情
import ContractAutograph from './pages/contract-system/contract-autograph';// 合同签订
import ContractFeedBack from './pages/contract-system/components/contract-feedback';// 合同签订结果页

// 司机端
import DriverMain from './pages/app-driver/main';
import DriverUser from './pages/app-driver/user';
import DriverWayOrder from './pages/app-driver/way-order';
import DriverCer from './pages/app-driver/driver-cer';
import FaceInput from './pages/app-driver/face-input';
import UploadFaceResult from './pages/app-driver/upload-face-result';
import ReceiptEdit from './pages/app-driver/receipt-edit'; // 修改回单
import ReceiptUpload from './pages/app-driver/receipt-upload'; // 上传回单
import DriverOrderDetail from './pages/app-driver/way-order/detail'; // 运单详情
import DriverAgreementSign from './pages/app-driver/main/components/agreement-sign';
// 车主端
import CarOwnerMain from './pages/app-car-owner/main'; // 首页
import CarOwnerOrder from './pages/app-car-owner/order'; // 运单列表
import CarOwnerUser from './pages/app-car-owner/user'; // 我的
import TruckCert from './pages/app-car-owner/truck-cert'; // 车辆认证
import OilCardPlatform from './pages/oil-card-platform'; // 油卡列表（缘多用油）
import WlRepair from './pages/wl-repair';
import CarOwnerTruckList from './pages/app-car-owner/user/my-truck-list'; // 我的车辆
import MyDrive from './pages/app-car-owner/user/my-driver'; // 车辆认证
import CarOrderDetail from './pages/app-car-owner/order/detail';
import DriverDetail from './components/driver_detail'; // 司机详情
import DetailDriverDetail from './components/detail_driver_detail'; // 运单司机详情，货主详情，车主详情
import WlRepairCardDetails from './pages/wl-repair/card-details';
import WlRepairTradeRecord from './pages/wl-repair/trade-record';
import WlRepairShareRecord from './pages/wl-repair/share-record';
import WlRepairShareAuthorize from './pages/wl-repair/share-authorize';
import OliCardDetails from './pages/oil-card-platform/oli-card-details'; // 油卡详情（缘多用油）
import OliCardTransactionsRecord from './pages/oil-card-platform/oil-card-transactions-record'; // 油卡交易记录（缘多用油）
import WriteOffDetails from './pages/oil-card-platform/write-off-for-oil/write-off-details';
import PumpOil from './pages/oil-card-platform/pump-oil'; // 拨油（缘多用油）
import OliCardShareRecord from './pages/oil-card-platform/oil-card-share-record'; // 油卡交易记录（缘多用油）
import Index from './pages/oil-card-platform/add-oil-authorize'; // 加油授权（缘多用油）
import OwnerCarDetail from './pages/app-car-owner/user/owner-car-detail'; // 车主端车辆详情
import SetDriver from './pages/app-car-owner/user/owner-car-detail/set-driver'; // 车主端 车辆详情 设置/更换司机
import OilOrderDetail from './pages/oil-card-platform/oil-card-order-detail'; // 油卡订单详情
import Order from './pages/oil-card-platform/oil-card-order'; // 油卡订单
import FictitiousOilCardOrderDetail from './pages/oil-card-platform/oil-card-order-detail/fictitious-oil-card-order-detail'; // 虚拟油卡订单详情
import InsuranceRouter from './insurance-router';

// 4s店
import FourStoreEntry from './pages/four-s-shop/car-entry'; // 4s店品牌入口
import FourBrandList from './pages/four-s-shop/car-list'; // 4s店品牌列表
import TruckDetails from './pages/four-s-shop/car-details';

// 货主端
import VehicleInfo from './pages/app-goods-owner/order/vehicle-info';
import WatermarkCameraView from './pages/watermark-camera';
import WatermarkCameraHistoryRecords from './pages/watermark-camera/watermark-camera-history-records';

const isAndroid = Platform.OS === 'android';

// 底部公共配置tabNavigator
const tabNavigatorOptions = {
  tabBarOptions: {
    labelStyle: {
      fontSize: 12,
    },
    allowFontScaling: false,
    activeBackgroundColor: '#fff',
    inactiveBackgroundColor: '#fff',
    activeTintColor: '#BA914A',
    style: {
      borderTopWidth: 1 / PixelRatio.get(),
      borderTopColor: '#F0EFEF',
    },
  },
  lazy: true,
  animationEnabled: false,
  swipeEnabled: false,
};

// header为空的属性
const emptyHeader = {
  header: null,
  navigationOptions: {
    header: null,
    headerBackTitle: null,
  },
};
// 标题局中
const titleCenter = {
  headerTitleStyle: {
    alignSelf: 'center',
    textAlign: 'center',
    flex: 1,
    paddingRight: isAndroid ? 56 : 0,
    fontSize: 18,
  },
};

// 司机端
const DriverTabNavigator = createBottomTabNavigator(
  {
    DriverMain: {
      screen: DriverMain,
    },
    DriverWayOrder: {
      screen: DriverWayOrder,
    },
    DriverUser: {
      screen: DriverUser,
    },
  },
  {
    initialRouteName: 'DriverMain',
    ...tabNavigatorOptions,
  },
);
// 车主端
const CarOwnerTabNavigator = createBottomTabNavigator(
  {
    CarOwnerMain: {
      screen: CarOwnerMain,
    },
    CarOwnerOrder: {
      screen: CarOwnerOrder,
    },
    CarOwnerUser: {
      screen: CarOwnerUser,
    },
  },
  {
    initialRouteName: 'CarOwnerMain',
    ...tabNavigatorOptions,
  },
);

// 路由页面
// 在新的页面被放入栈顶之后，StackNavigator 给你的应用程序提供了切换页面的方法。
// 在 iOS 与 Android 平台上，StackNavigator 默认对应着它们各自的风格，
// 比如在 iOS 上新的页面从右侧滑入，而在 Android 上则是从底部淡入。
const AppNavigator = createStackNavigator(
  {

    // 司机端3个tab页面
    DriverTab: {
      screen: DriverTabNavigator,
      navigationOptions: {
        header: null,
        headerBackTitle: null,
      },
    },

    // 车主端3个tab页面
    // 货主端4个tab页面
    // GoodsOwnerTab: {
    //   screen: GoodsOwnerTabNavigator,
    //   navigationOptions: {
    //     header: null,
    //     headerBackTitle: null,
    //   },
    // },
    CarOwnerTab: {
      screen: CarOwnerTabNavigator,
      navigationOptions: {
        header: null,
        headerBackTitle: null,
      },
    },
    RoleSwitch: {
      screen: RoleSwitch,
      ...emptyHeader,
    },
    Setting: {
      screen: Setting,
      navigationOptions: {
        headerTitle: '设置',
        ...titleCenter,
      },
    },
    UserFeedback: {
      screen: UserFeedback,
      navigationOptions: {
        headerTitle: '意见反馈',
        ...titleCenter,
      },
    },
    LoginView: {
      screen: LoginView,
      ...emptyHeader,
    },
    DriverCer: {
      screen: DriverCer,
      navigationOptions: {
        headerTitle: '司机认证',
        ...titleCenter,
      },
    },
    FaceInput: {
      screen: FaceInput,
      navigationOptions: {
        headerTitle: '人脸信息录入',
        ...titleCenter,
      },
    },
    UploadFaceResult: {
      screen: UploadFaceResult,
      navigationOptions: {
        headerTitle: '人脸信息录入',
        ...titleCenter,
      },
    },
    // 修改回单
    ReceiptEdit: {
      screen: ReceiptEdit,
      navigationOptions: {
        headerTitle: '修改回单',
        ...titleCenter,
      },
    },
    // 上传回单
    ReceiptUpload: {
      screen: ReceiptUpload,
      navigationOptions: {
        headerTitle: '上传回单',
        ...titleCenter,
      },
    },
    DriverOrderDetail: {
      screen: DriverOrderDetail,
      navigationOptions: {
        headerTitle: '运单详情',
        ...titleCenter,
      },
    },
    DriverAgreementSign: {
      screen: DriverAgreementSign,
      navigationOptions: {
        headerTitle: '保密协议签署',
        ...titleCenter,
      },
    },
    Welcome: {
      screen: Welcome,
      ...emptyHeader,
    },
    FeedBackDriverCer: {
      screen: FeedBackDriverCer,
      navigationOptions: {
        header: null,
        gesturesEnabled: false,
      },
    },
    CustAgreement: {
      screen: CustAgreement,
      ...emptyHeader,
    },
    IdCardCertif: {
      screen: IdCardCertif,
      navigationOptions: {
        headerTitle: '实名认证',
        ...titleCenter,
      },
    },
    CertificationProgress: {
      screen: CertificationProgress,
      navigationOptions: {
        headerTitle: '司机认证',
        ...titleCenter,
      },
    },
    ContractSYSList: {
      screen: ContractSYSList,
      navigationOptions: {
        headerTitle: '合同及协议',
        ...titleCenter,
      },
    },
    ContractDetail: {
      screen: ContractDetail,
      ...emptyHeader,
    },
    ContractAutograph: {
      screen: ContractAutograph,
      ...emptyHeader,
    },
    ContractFeedBack: {
      screen: ContractFeedBack,
      navigationOptions: {
        ...titleCenter,
        gesturesEnabled: false,
      },
    },
    AccountCenter: {
      screen: AccountCenter,
      navigationOptions: {
        headerTitle: '账号安全',
        ...titleCenter,
      },
    },
    ChangePhone: {
      screen: ChangePhone,
      ...emptyHeader,
    },
    ChangePhoneNew: {
      screen: ChangePhoneNew,
      ...emptyHeader,
    },
    ChangePhoneConform: {
      screen: ChangePhoneConform,
      ...emptyHeader,
    },
    Test: {
      screen: Test,
      navigationOptions: {
        headerTitle: '测试页面',
        ...titleCenter,
      },
    },
    ListViewDemo: {
      screen: ListViewDemo,
      navigationOptions: {
        headerTitle: '列表',
        ...titleCenter,
      },
    },
    IQKeyboardManager: {
      screen: IQKeyboardManager,
      navigationOptions: {
        headerTitle: 'IQKeyboardManager',
        ...titleCenter,
      },
    },
    InputMobile: {
      screen: InputMobile,
      navigationOptions: {
        headerTitle: '重置密码',
        ...titleCenter,
      },
    },
    InputCode: {
      screen: InputCode,
      navigationOptions: {
        headerTitle: '重置密码',
        ...titleCenter,
      },
    },
    SetPassword: {
      screen: SetPassword,
      navigationOptions: {
        headerTitle: '重置密码',
        ...titleCenter,
      },
    },
    MobileBind: {
      screen: MobileBind,
      navigationOptions: {
        header: null,
        headerBackTitle: null,
        gesturesEnabled: false,
      },
    },
    FourStoreEntry: {
      screen: FourStoreEntry,
      ...emptyHeader,
    },
    FourBrandList: {
      screen: FourBrandList,
      navigationOptions: {
        ...titleCenter,
      },
    },
    TruckDetails: {
      screen: TruckDetails,
      navigationOptions: {
        headerTitle: '车辆详情',
        ...titleCenter,
      },
    },
    VehicleInfo: {
      screen: VehicleInfo,
      navigationOptions: {
        headerTitle: '车辆详情',
        ...titleCenter,
      },
    },
    TruckCert: {
      screen: TruckCert,
      navigationOptions: {
        headerTitle: '车辆入驻',
        ...titleCenter,
      },
    },
    OilCardPlatform: {
      screen: OilCardPlatform,
      ...emptyHeader,
    },
    WlRepair: {
      screen: WlRepair,
      navigationOptions: {
        headerTitle: '修理卡',
        ...titleCenter,
      },
    },
    CarOwnerTruckList: {
      screen: CarOwnerTruckList,
      ...emptyHeader,
    },
    MyDrive: {
      screen: MyDrive,
      ...emptyHeader,
    },
    CarOrderDetail: {
      screen: CarOrderDetail,
      navigationOptions: {
        headerTitle: '运单详情',
        ...titleCenter,
      },
    },
    DriverDetail: {
      screen: DriverDetail,
      ...emptyHeader,
    },
    DetailDriverDetail: {
      screen: DetailDriverDetail,
      ...emptyHeader,
    },
    WlRepairCardDetails: {
      screen: WlRepairCardDetails,
      navigationOptions: {
        headerTitle: '维修卡详情',
        ...titleCenter,
      },
    },
    WlRepairTradeRecord: {
      screen: WlRepairTradeRecord,
      ...emptyHeader,
    },
    WlRepairShareRecord: {
      screen: WlRepairShareRecord,
      navigationOptions: {
        headerTitle: '共享记录',
        ...titleCenter,
      },
    },
    WlRepairShareAuthorize: {
      screen: WlRepairShareAuthorize,
      navigationOptions: {
        headerTitle: '共享修理卡',
        ...titleCenter,
      },
    },
    OliCardDetails: {
      screen: OliCardDetails,
      navigationOptions: {
        headerTitle: '油卡详情',
        ...titleCenter,
      },
    },
    OliCardTransactionsRecord: {
      screen: OliCardTransactionsRecord,
      navigationOptions: {
        ...emptyHeader,
      },
    },
    WriteOffDetails: {
      screen: WriteOffDetails,
      navigationOptions: {
        ...emptyHeader,
      },
    },
    PumpOil: {
      screen: PumpOil,
      navigationOptions: {
        headerTitle: '申请拨油',
        ...titleCenter,
      },
    },
    OliCardShareRecord: {
      screen: OliCardShareRecord,
      navigationOptions: {
        headerTitle: '共享记录',
        ...titleCenter,
      },
    },
    AddOilAuthorize: {
      screen: Index,
      navigationOptions: {
        headerTitle: '加油授权',
        ...titleCenter,
      },
    },
    OwnerCarDetail: {
      screen: OwnerCarDetail,
      ...emptyHeader,
    },
    SetDriver: {
      screen: SetDriver,
      navigationOptions: {
        headerTitle: '选择司机',
        ...titleCenter,
      },
    },
    OilOrderDetail: {
      screen: OilOrderDetail,
      navigationOptions: {
        header: null,
        headerBackTitle: null,
        gesturesEnabled: false,
      },
    },
    Order: {
      screen: Order,
      navigationOptions: {
        ...emptyHeader
      },
    },
    FictitiousOilCardOrderDetail: {
      screen: FictitiousOilCardOrderDetail,
      ...emptyHeader,
    },
    // 保险router
    ...InsuranceRouter,
    WatermarkCameraView: {
      screen: WatermarkCameraView,
      ...emptyHeader,
    },
    WatermarkCameraHistoryRecords: {
      screen: WatermarkCameraHistoryRecords,
      navigationOptions: {
        headerTitle: '历史相册',
        ...titleCenter,
      },
    },

  },
  {
    // initialRouteName:__DEV__ ? 'Test' : 'BootPage',
    initialRouteName: 'Welcome',

    transitionConfig: () => ({
      // 将安卓的跳转动画改成iOS
      // 只要修改最后的forVertical就可以实现不同的动画了。
      // 从右向左：forHorizontal   从下向上：forVertical 安卓那种的从下向上：forFadeFromBottomAndroid； 无动画：forInitial
      screenInterpolator: StackViewStyleInterpolator.forHorizontal,
    }),
    defaultNavigationOptions: {
      headerStyle: {
        // backgroundColor: '#f4511e',
        elevation: 0,
        borderBottomWidth: 1 / PixelRatio.get(),
        borderBottomColor: '#F0EFEF',
        height: px2dp(88),
        // paddingBottom: isAndroid ? 2 : 0,
        // marginLeft: isAndroid ? 0 : 14
      },
      headerTintColor: '#000',
      // headerTitleStyle: {
      //   fontWeight: 'bold',
      // },
      headerLeft: <BackImageOn />,
      headerBackTitle: null,
      // headerBackImage: <BackImageOn />,
    },
    // //  指定标题栏的渲染方式
    // // screen：每个页面都有各自的标题栏，并且伴随着页面切换一起淡入淡出。这是 Android 上的常见模式。
    headerMode: 'screen',
    // // 用于屏幕的默认导航选项
    // navigationOptions: {
    //     headerBackTitle: null,
    //     header: null
    // },
    //  当切换动画结束时调用的函数
    onTransitionEnd: async () => { },
  },
);

export const AppContainer = createAppContainer(AppNavigator);

const defaultGetStateForAction = AppNavigator.router.getStateForAction;

AppNavigator.router.getStateForAction = (action, state) => {
  if (__DEV__) {
    console.log('wangtao:action----->', action);
    console.log('wangtao:state----->', state);
  }

  if (state && action.type === 'replace') {
    // 替换当前路由,如果当前路由存在栈中,则删除栈中存在的路由
    let routes = [];
    const index = action.index || 1;
    if (state.routes.length > 1) {
      routes = state.routes.filter((r) => r.routeName !== action.routeName);
      routes = routes.slice(0, routes.length - index);
      const { routeName, ...other } = action;
      const route = {
        routeName,
        params: other,
        key: Math.random().toString(),
      };
      routes.push(route);
      return {
        ...state,
        routes,
        index: routes.length - 1,
      };
    }
    return defaultGetStateForAction(NavigationActions.init());
  }
  if (state && action.type === 'refresh') {
    // 刷新当前页面
    const { routes } = state;
    routes[state.routes.length - 1].key = Math.random().toString();
    return {
      ...state,
      routes,
      index: routes.length - 1,
    };
  }
  if (state && action.type === 'backToTop') {
    // 返回首页
    if (state.routes.length <= 1 || state.routes[0].routeName === 'LoginView') {
      return defaultGetStateForAction(NavigationActions.init());
    }
    const routes = state.routes.slice(0, 1);
    state.routes = routes;
    routes[0].key = Math.random().toString();
    routes[0].index = 0;
    if (routes[0].routes && routes[0].routes.length > 0) {
      routes[0].routes[0].params = action.params;
    }
    return {
      ...state,
      routes,
      index: routes.length - 1,
    };
  }
  if (state && action.type === 'refreshRoute') {
    // 刷新栈中指定名称路由,如果不存在,则不进行任何操作
    const { routes } = state;
    const index = routes.findIndex((r) => r.routeName === action.routeName);
    if (index >= 0) {
      routes[index].key = Math.random().toString();
    }
    return {
      ...state,
      routes,
      index: routes.length - 1,
    };
  }
  if (state && action.type === 'refreshRoutes') {
    // 刷新栈中指定名称路由,如果不存在,则不进行任何操作
    const names = action.routeNames;
    const routes = state.routes.map((r) => {
      if (names.some((n) => n === r.routeName)) {
        r.key = Math.random().toString();
      }
      return r;
    });
    return {
      ...state,
      routes,
      index: routes.length - 1,
    };
  }

  if (action.params && action.params.routerFrom) {
    const { routerFrom } = action.params;
    const { routeName, ...other } = action;
    let routes = [];
    routes.push({
      routeName: 'DriverTab',
      index: 2,
      key: Math.random().toString(),
      routes: [
        { key: 'DriverMain', routeName: 'DriverMain', params: undefined },
        { key: 'DriverWayOrder', routeName: 'DriverWayOrder', params: undefined },
        { key: 'DriverUser', routeName: 'DriverUser', params: undefined },
      ],
    });
    // 司机认证
    if (routerFrom === 'FeedBackDriverCer' && routeName === 'CertificationProgress') {
      routes.push({
        routeName: 'CertificationProgress',
        params: other.params,
        key: Math.random().toString(),
      });
      return {
        ...state,
        routes,
        index: routes.length - 1,
      };
    }
  }

  return defaultGetStateForAction(action, state);
};
